<template>
	<view class="cu-form-group">
		<view   :class="['grid col-4 grid-square flex-sub',colClass]">
			<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
				<image :src="imgList[index]" mode="aspectFill"></image>
				<view class="cu-tag bg-red" @tap.stop="DelImg(index)">
					<text class='cuIcon-close'></text>
				</view>
			</view>
			<view class="solids" @tap="ChooseImage" v-if="imgList.length<max">
				<text class='cuIcon-cameraadd'></text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name:'img-upload',
		props: {
			apiUrl:{
				type:String,
				default:'/api/file/photo/upload'
			},
			colClass:{
				type:String,
			},
			imgs: {
				type:Array,
				default:()=>[]
			},
			max: {
				type: Number,
				default:3
			}
		},
		data() {
			return {
				imgList:[]
			}
		},
		watch:{
			imgs:{
				handler:function(val){
					if(val){
						this.imgList=val
					}
				},
				immediate: true
			}
		},
		methods: {
			ChooseImage:function(){
				let that =this
				let cunt = this.max - this.imgList.length;
				uni.chooseImage({
					count: cunt,  
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], // 从相册选择
					success: (res) => {
						res.tempFilePaths.map((item) => {
							that.uploadImages(item,that);
						});
					}
				});
			},
			uploadImages:function(filePath,that) {
				uni.showLoading({
					title: '图片获取中...',
					mask: true
				});
				let host = this.$host;
				let _url = this.apiUrl;
				uni.uploadFile({
					url: host + _url, // /DriverPlatform
					filePath: filePath,
					header: {
						'Authorization': uni.getStorageSync('Authorization')
					},
					name: 'file',
					complete(result) {
						uni.hideLoading();
						switch (result.statusCode) {
							case 200:
								let data = JSON.parse(result.data);

								if (data.success) {
									that.imgList.push(data.data);
									that.$emit('change', that.imgList)
								} else {
									uni.showToast({
										title: data.info,
										icon: 'none'
									});
								}
								break;
							case 413:
								uni.showToast({
									title: '文件过大，请重新上传，单个文件大小小于2M',
									icon: 'none'
								});
							case 405:
								uni.navigateTo({
									url: '/pages/login/login'
								})
						}
					}
				})
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(index) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认移除该图片？',
					success: function(res) {
						if (res.confirm) {
							that.imgList.splice(index, 1)
							that.$emit('change', that.imgList)
						}
					}
				});
			}
		}
	}
</script>

<style>

</style>